var all_data = {};
var response_data;
var tableData = [];

var player = 0;

var mindmap_jsonData1 =
{
    "id": "1",
    "key_words": "Root Node",
    "start_time": "0.0",
    "end_time": "341",
    "children": [
        {
            "id": "1.1",
            "key_words": "太阳的辐射",
            "start_time": "0.0",
            "end_time": "341",
            "children": [
                {
                    "id": "1.1.1",
                    "key_words": "太阳的地位和性质",
                    "start_time": "2.839999999999997",
                    "end_time": "326.26",
                    "children": [
                        {
                            "id": "1.1.1.1",
                            "key_words": "太阳系中心天体地位",
                            "start_time": "9",
                            "end_time": "19",
                            "children": []
                        },
                        {
                            "id": "1.1.1.2",
                            "key_words": "太阳的质量、体积、密度和组成",
                            "start_time": "2.839999999999997",
                            "end_time": "326.26",
                            "children": [
                                {
                                    "id": "1.1.1.2.1",
                                    "key_words": "太阳质量占比和体积关系",
                                    "start_time": "36.0",
                                    "end_time": "41.5",
                                    "children": []
                                },
                                {
                                    "id": "1.1.1.2.2",
                                    "key_words": "太阳的密度比较",
                                    "start_time": "2.839999999999997",
                                    "end_time": "326.26",
                                    "children": []
                                },
                                {
                                    "id": "1.1.1.2.3",
                                    "key_words": "太阳的组成（清和垃）",
                                    "start_time": "2.839999999999997",
                                    "end_time": "326.26",
                                    "children": []
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "1.1.2",
                    "key_words": "太阳的结构",
                    "start_time": "0.0",
                    "end_time": "341",
                    "children": [
                        {
                            "id": "1.1.2.1",
                            "key_words": "从内到外的结构",
                            "start_time": "0.0",
                            "end_time": "209.2",
                            "children": [
                                {
                                    "id": "1.1.2.1.1",
                                    "key_words": "合反应区",
                                    "start_time": "9.219999999999997",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.2",
                                    "key_words": "对牛区",
                                    "start_time": "158.94",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.3",
                                    "key_words": "佛社区",
                                    "start_time": "158.94",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.4",
                                    "key_words": "大气层",
                                    "start_time": "0.0",
                                    "end_time": "2.22",
                                    "children": []
                                }
                            ]
                        },
                        {
                            "id": "1.1.2.2",
                            "key_words": "结构顺序的修正",
                            "start_time": "340",
                            "end_time": "341",
                            "children": []
                        }
                    ]
                }
            ]
        }
    ]
};


var mindmap_jsonData2 = {
    "id": "1",
    "key_words": "Root Node",
    "start_time": "0.0",
    "end_time": "341",
    "children": [
        {
            "id": "1.1",
            "key_words": "太阳的辐射",
            "start_time": "0.0",
            "end_time": "341",
            "children": [
                {
                    "id": "1.1.1",
                    "key_words": "太阳的地位和性质",
                    "start_time": "2.839999999999997",
                    "end_time": "326.26",
                    "children": [
                        {
                            "id": "1.1.1.1",
                            "key_words": "太阳系中心天体地位",
                            "start_time": "9",
                            "end_time": "19",
                            "children": []
                        },
                        {
                            "id": "1.1.1.2",
                            "key_words": "太阳的质量、体积、密度和组成",
                            "start_time": "2.839999999999997",
                            "end_time": "326.26",
                            "children": [
                                {
                                    "id": "1.1.1.2.1",
                                    "key_words": "太阳质量占比和体积关系",
                                    "start_time": "36.0",
                                    "end_time": "41.5",
                                    "children": []
                                },
                                {
                                    "id": "1.1.1.2.2",
                                    "key_words": "太阳的密度比较",
                                    "start_time": "2.839999999999997",
                                    "end_time": "326.26",
                                    "children": []
                                },
                                {
                                    "id": "1.1.1.2.3",
                                    "key_words": "太阳的组成（清和垃）",
                                    "start_time": "2.839999999999997",
                                    "end_time": "326.26",
                                    "children": []
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "1.1.2",
                    "key_words": "太阳的结构",
                    "start_time": "0.0",
                    "end_time": "341",
                    "children": [
                        {
                            "id": "1.1.2.1",
                            "key_words": "从内到外的结构",
                            "start_time": "0.0",
                            "end_time": "209.2",
                            "children": [
                                {
                                    "id": "1.1.2.1.1",
                                    "key_words": "合反应区",
                                    "start_time": "9.219999999999997",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.2",
                                    "key_words": "对牛区",
                                    "start_time": "158.94",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.3",
                                    "key_words": "佛社区",
                                    "start_time": "158.94",
                                    "end_time": "209.2",
                                    "children": []
                                },
                                {
                                    "id": "1.1.2.1.4",
                                    "key_words": "大气层",
                                    "start_time": "0.0",
                                    "end_time": "2.22",
                                    "children": []
                                }
                            ]
                        },
                        {
                            "id": "1.1.2.2",
                            "key_words": "结构顺序的修正",
                            "start_time": "340",
                            "end_time": "341",
                            "children": []
                        }
                    ]
                }
            ]
        },
        {
            "id": "1.2",
            "key_words": "相关立体",
            "start_time": "0",
            "end_time": "341",
            "children": [
                {
                    "id": "1.2.1",
                    "key_words": "太阳系的中心天体",
                    "start_time": "2.839999999999997",
                    "end_time": "331.58",
                    "children": [
                        {
                            "id": "1.2.1.1",
                            "key_words": "原因与结果的关系",
                            "start_time": "2.839999999999997",
                            "end_time": "331.58",
                            "children": [
                                {
                                    "id": "1.2.1.1.1",
                                    "key_words": "太阳的质量对其位置的影响",
                                    "start_time": "2.839999999999997",
                                    "end_time": "331.58",
                                    "children": []
                                },
                                {
                                    "id": "1.2.1.1.2",
                                    "key_words": "中心天体的定义与实际位置的关系",
                                    "start_time": "2.839999999999997",
                                    "end_time": "331.58",
                                    "children": []
                                }
                            ]
                        }
                    ]
                },
                {
                    "id": "1.2.2",
                    "key_words": "太阳的主要成分",
                    "start_time": "340",
                    "end_time": "341",
                    "children": [
                        {
                            "id": "1.2.2.1",
                            "key_words": "清和垃的构成",
                            "start_time": "340",
                            "end_time": "341",
                            "children": []
                        }
                    ]
                },
                {
                    "id": "1.2.3",
                    "key_words": "太阳能量的来源与转化",
                    "start_time": "0",
                    "end_time": "337.32",
                    "children": [
                        {
                            "id": "1.2.3.1",
                            "key_words": "太阳内部的合聚变反应",
                            "start_time": "0",
                            "end_time": "322",
                            "children": []
                        },
                        {
                            "id": "1.2.3.2",
                            "key_words": "质量与能量的转化关系",
                            "start_time": "2.839999999999997",
                            "end_time": "337.32",
                            "children": [
                                {
                                    "id": "1.2.3.2.1",
                                    "key_words": "太阳能量来源与质量损失关系",
                                    "start_time": "292.96",
                                    "end_time": "337.32",
                                    "children": []
                                },
                                {
                                    "id": "1.2.3.2.2",
                                    "key_words": "太阳的生命周期",
                                    "start_time": "2.839999999999997",
                                    "end_time": "326.26",
                                    "children": []
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "id": "1.3",
            "key_words": "总结与结束",
            "start_time": "0",
            "end_time": "341",
            "children": [
                {
                    "id": "1.3.1",
                    "key_words": "注意：对太阳的结构、性质、以及能量转化过程的理解是重点，需要清晰把握太阳在太阳系中的地位，以及其对周围天体的影响。",
                    "start_time": "0",
                    "end_time": "341",
                    "children": []
                }
            ]
        }
    ]
}

;


function renderVideo(videourl){

    if(player == 0){
        player = new Aliplayer({
            "id": "rightBottomRow",
            // 指定要播放的视频文件的URL。请将 "your-video-source.mp4" 替换为你的视频文件URL。
            "source": videourl,
            "width": "83%",
            "height": "88%",
        
            // 设置是否自动播放。false表示不自动播放，true表示自动播放。
            "autoplay": true,
        
            // 设置是否支持重播。false表示不支持，true表示支持。
            "rePlay": false,
        
            // 设置是否在移动端内联播放。true表示内联播放，false表示在全屏播放。
            "playsinline": true,
        
            // 设置是否预加载视频。true表示预加载，false表示不预加载。
            "preload": true,
        
            // 设置控制条的可见性。"click"表示点击时可见，其他选项可查阅阿里云文档。
            "controlBarVisibility": "click",
        
            // 使用H5 Prism播放器。true表示使用H5播放器，false表示不使用。
            "useH5Prism": true,
        
            },
            );
    }else{
        player.loadByUrl(videourl);
    }


}


//思维导图渲染函数
function renderMindMap(jsonData){

    var container_map = document.getElementById("contentContainer");
    
    var max_lines = 0;
    var nodes_convert = new vis.DataSet();
    var edges_convert = new vis.DataSet();

    // 模拟 JSON 数据
    function countDots(inputString) {
      // 使用正则表达式匹配字符串中的点号，并返回匹配的个数
      var matches = inputString.match(/\./g);
      if (matches) {
        return matches.length;
      } else {
        return 0;
      }
    }

    function convertJsonToVisData(jsonData, parentNodeId) {
        var nodes = [];
        var edges = [];

        for (var i = 0; i < jsonData.length; i++) {
            var node = jsonData[i];
            var nodeId = node.id;
            // var label = node.key_words;
            var href = node.href; // 添加链接属性
            var start_time = node.start_time;
            var class_num = 4-countDots(nodeId);
            var level = 4 - class_num;
            var keyWords= node.key_words;
            var colors = ["#d5ebe3","#fceaea","#c3ddf6","#87ab69","#75975e","#658354"]
            var label = ''; // 初始化 label

            for (var k = 0; k < keyWords.length; k++) {
            label += keyWords[k];
            var temp_max_lines = 0;
            if (((k + 1) % 8 === 0)&&k<keyWords.length-2) {
                label += '\n'; // 在每6个字符后添加一个换行符
                temp_max_lines += 1;
                if(temp_max_lines > max_lines){
                    max_lines = temp_max_lines;
                }
            }
            }
            if(max_lines < 1){
                max_lines = 1;
            }

            nodes.push({ level:level,id: nodeId, label: label, href: href ,start_time: start_time,class_num:class_num});
           
            if (parentNodeId) {
                
                edges.push({ from: parentNodeId, to: nodeId ,class_num:class_num,level:level});
            }

            if (node.children && node.children.length > 0) {
                var childData = convertJsonToVisData(node.children, nodeId);
                nodes = nodes.concat(childData.nodes);
                edges = edges.concat(childData.edges);
            }
        }

        return { nodes: nodes, edges: edges };
    }

    
    var visData = convertJsonToVisData([jsonData], null);

    //将json数据转化适合渲染的数据对象
    function data_convert(visData){
        var nodes = visData.nodes
        var edges = visData.edges
        var colors_div = ['#d5ebe3','#fceaea','#c3ddf6','#87ab69','#75975e','#658354']
        var colors_div2 = ['#9ab69f','#decece','#c3ddf6','#87ab69','#75975e','#658354']
        
        //节点数据转化
        for(let i = 0; i < nodes.length; i++){
            let node = nodes[i];
            let node_convert ={
                id:node.id,
                level:node.level,
                label:node.label,
                href:node.href,
              
                start_time : node.start_time,
                color: {
                    border: colors_div2[node.level],
                    background: colors_div[node.level],
                    highlight: {
                    border: '#',
                    background: '#ffd81b'
                    }
                },
                
                scaling: {
                    min: 10,
                    max: 440,
                    label: {
                    enabled: false,
                    min: 554,
                    max: 3550,
                    maxVisible: 3550,
                    drawThreshold:5
                    },
                },
                title: "点击可跳转",
                font: {
            
                    size: node.class_num * 12, // 字体大小
                    color: 'black', // 字体颜色
                    face: 'Arial' ,// 字体类型
                    
                    bold:true,
                    multi: false,
                    vadjust: 5,
                    mod: 'bold'
             
                },
                shape:'box',
                
            }
            nodes_convert.add(node_convert);
        }

        //边数据转化
        for(let i = 0; i < edges.length; i++){
            let edge = edges[i];
            let edge_convert ={
                from:edge.from,
                to:edge.to,
                length:100,
                color:{
                    color:colors_div2[edge.level-1],
                   
                },
                width:edge.class_num *5,
                smooth: {
                    type: "cubicBezier",
                    forceDirection: "horizontal",
                    
                  },
                
               
            }
            edges_convert.add(edge_convert);
        }
    }

    //转化数据
    data_convert(visData);
    // 创建 Vis Network 数据对象
    var data_mind = {
        nodes: nodes_convert,
        edges: edges_convert
    };


    var layout = {
        hierarchical: {
            direction: "LR", // 默认从左到右布局
            levelSeparation: max_lines * 550,  

                 
        },  
    };



   var network = new vis.Network(container_map, data_mind,{layout});




    // 添加事件监听器，以在节点被单击时打开链接
    network.on("click", function (params) {
        if (params.nodes.length > 0) {
            var selectedNodeId = params.nodes[0];
            var selectedNode = data_mind.nodes.get(selectedNodeId);
            var startTime = selectedNode.start_time;
        

            // 阻止默认行为，防止导航到链接地址
        
            // 跳转到视频时间
            jumpToVideoTime(startTime);
            }
        });

    function jumpToVideoTime(jumpTime) {

        // 将毫秒转换为秒
        var jumpSeconds = jumpTime;

        
        // // 发送消息到content.js
        // chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        //     chrome.tabs.sendMessage(tabs[0].id, { action: "videoplayerjump",data:jumpSeconds});
        //   });

       
    } 
}


// 生成不同颜色的函数
function generateColor(index) {
    var colors = ['#ffcccc', '#ccffcc', '#ccccff', '#ffd699', '#99ffcc'];
    return colors[index % colors.length];
}

function reload(){
    // 获取表格的 tbody 元素

    var tableBody = document.getElementById("tableBody");

    // 遍历数据，动态生成表格内容
    tableData.forEach(function (row,index) {
        // 创建表格行
        var tableRow = document.createElement("tr");
        tableRow.style.backgroundColor = generateColor(index);

        // 遍历行数据，创建表格单元格
        for (var key in row) {
            if (row.hasOwnProperty(key)) {
                var linkCell = document.createElement("td");
                var linkElement = document.createElement("a");
                linkElement.textContent = row.cell;

                linkElement.style.cursor = "grab";
                
                // 添加点击事件处理程序
                linkElement.addEventListener("click", function(event) {
                    // 阻止默认跳转行为
                    event.preventDefault();

                    let videourl = "../videos/" + linkElement.textContent + ".mp4"

                    renderVideo(videourl);

                    // 在这里执行你的自定义点击事件逻辑
                    renderMindMap(all_data[linkElement.textContent]);
                });
                linkCell.appendChild(linkElement);
        
                // 将链接单元格添加到表格行
                tableRow.appendChild(linkCell);
            }
        }

        // 将表格行添加到 tbody 中
        tableBody.appendChild(tableRow);
    });
}


function getBackData(relatedlabel){
    console.log("联查调试6")
    return new Promise((resolve, reject) => {
        // 构建要发送的数据对象
    const requestData = {
        node: relatedlabel
    };
    fetch("http://127.0.0.1:8090/liancha", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestData),
    })
      .then(response => {
        if (response.ok) {
          return response.json();

        } else {
          reject('请求失败');
        }
      })
      .then(data => {
        let temp_data = data['video_data']
        // console.log(temp_data)
        // temp_data = temp_data.video_data
        for(let i = 0; i < temp_data.length; i++){
            let key = temp_data[i]['name'];
            let data = JSON.parse(temp_data[i]['treejson'])
            // console.log(key)
            // console.log(data)
            all_data[key] = data        
        }

      })
      .then(response =>{
        
        Object.keys(all_data).forEach(function(key) {
            var row = {};
            row['cell'] = key;
            
            // 添加更多单元格数据，这里假设要添加的数据都是一样的
            // 如果有不同的数据，需要根据具体情况进行修改
            tableData.push(row);
        })
        
            reload();
      })
      .catch(error => {
        window.alert("未找到关联课程，请重试！")
      });
  });
}

// function getBackData(relatedlabel){
//     all_data = {"太阳的概况":mindmap_jsonData1,"太阳的结构":mindmap_jsonData2}
// }

function relatedlabelsend(relatedlabel){

    // getBackData(relatedlabel)
    // .then(all_data => {
    //     Object.keys(all_data).forEach(function(key) {
    //         var row = {};
    //         row['cell'] = key;
    //         // 添加更多单元格数据，这里假设要添加的数据都是一样的
    //         // 如果有不同的数据，需要根据具体情况进行修改
    //         tableData.push(row);
    //     });

            getBackData(relatedlabel)
            // all_data = {"太阳的概况":mindmap_jsonData1,"太阳的结构":mindmap_jsonData2}

            // console.log(all_data)
            

      



    // 执行后台任务
    // all_data = {"大数据背景下数据管理面临的挑战":mindmap_jsonData,"系统生态圈":mindmap_jsonData};
    // tableData = Object.keys(all_data);

}

window.addEventListener('storage', function(event) {


    if (event.key === 'related_video') { // 监听特定的键值
        let relatedlabel = event.newValue
        console.log(relatedlabel)
        relatedlabelsend(relatedlabel)
        
    }

});


document.addEventListener('DOMContentLoaded', function () {


const closeButton = document.getElementById("close_button");
closeButton.addEventListener("click",function(){
    let iframe = window.parent.document.getElementById('relatedvideos')
    iframe.parentElement.removeChild(iframe)
});




})